﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Xml.Serialization;

namespace Editor
{
    public class Board
    {
        private int _rows;
        private int _columns;
        private Bitmap filler = new Bitmap(32, 32);
        [XmlIgnore]
        public Bitmap _board;
        private Graphics _imageDrawer;
        public List<CompleteTile[]> Rows = new List<CompleteTile[]>();
        public Board(int Rows, int Columns)
        {
            _board = new Bitmap(Columns * 32, Rows * 32);
            _imageDrawer = Graphics.FromImage(_board);
            _rows = Rows;
            _columns = Columns;
            CreateBlankTile();
            Init();
            _imageDrawer.Clear(Color.Black);
        }
        private void CreateBlankTile()
        {
            Graphics g = Graphics.FromImage(filler);
            g.FillRegion(Brushes.Black, new Region(new Rectangle(0, 0, 32, 32)));
            g.Dispose();
        }
        private void Init()
        {
            for (int i = 0; i < _rows; i++)
            {
                Rows.Add(new CompleteTile[_columns]);
                for (int x = 0; x < _columns; x++)
                {
                    Rows[i][x] = new CompleteTile();
                    Rows[i][x].tileImage = filler;
                }
            }
        }
        public void ReDrawBoard()
        {
            for (int i = 0; i < _rows; i++)
            {
                for (int x = 0; x < _columns; x++)
                {
                    try
                    {
                        _imageDrawer.DrawImage(Rows[i][x].tileImage, new Rectangle(x * 32, i * 32, 32, 32), new Rectangle(0, 0, 32, 32), GraphicsUnit.Pixel);
                    }
                    catch
                    {
                    }
                }
            }
        }
        public void ChangeTile(int Row, int Column, iTile tile)
        {
            Rows[Row][Column] = (CompleteTile)tile;
            _imageDrawer.DrawImage(Rows[Row][Column].tileImage, new Rectangle(Column * 32, Row * 32, 32, 32), new Rectangle(0, 0, 32, 32), GraphicsUnit.Pixel);
        }
        public void Save(ref FileStream fileStream)
        {
            Type[] types = new Type[2]{ (typeof(CompleteTile)),(typeof(CompleteTile[]))};
            XmlSerializer serializer = new XmlSerializer(typeof(List<CompleteTile[]>),types);
            try
            {
                serializer.Serialize(fileStream, Rows);
            }
            catch { }
            fileStream.Close();
        }
    }
}
